<?php

namespace app\api\controller\v1;

use app\common\controller\Api;



/**
 * Token接口
 */
class Message extends Api
{
    protected $noNeedLogin = ['get'];
    protected $noNeedRight = '*';

    public function get()
    {
        define("TOKEN", "adigh2g2gj11ghkrfk1");  //填写自己的token

        if (isset($_GET['echostr'])) {            //校验服务器地址URL
            $this->valid();
        } else {
            $this->responseMsg();
        }

    }
    protected function valid()
    {
        $echoStr = $_GET["echostr"];
        if ($this->checkSignature()) {
            header('content-type:text');
            echo $echoStr;
            exit;
        } else {
            echo $echoStr . '+++' . TOKEN;
            exit;
        }

    }

    protected function responseMsg()
    {
        $postStr = file_get_contents('php://input');   //此处推荐使用file_get_contents('php://input')获取后台post过来的数据

        if (!empty($postStr) && is_string($postStr)) {
            $postArr = json_decode($postStr, true);
            if (!empty($postArr['MsgType']) && $postArr['MsgType'] == 'text') {   //用户发送文本消息
                $fromUsername = $postArr['FromUserName'];   //发送者openid
                $media_id = '';   //输入想要回复的图片消息的media_id
                $data = array(
                    "touser" => $fromUsername,
                    "msgtype" => "image",
                    "image" => array("media_id" => $media_id)
                );
                $json = json_encode($data, JSON_UNESCAPED_UNICODE);  //php5.4+
                $this->requestAPI($json);
            } elseif (!empty($postArr['MsgType']) && $postArr['MsgType'] == 'image') { //用户发送图文消息
                $fromUsername = $postArr['FromUserName'];   //发送者openid
                $media_id = '';   //输入想要回复的图片消息的media_id
                $data = array(
                    "touser" => $fromUsername,
                    "msgtype" => "image",
                    "image" => array("media_id" => $media_id)
                );
                $json = json_encode($data, JSON_UNESCAPED_UNICODE);  //php5.4以上版本才可使用
                $this->requestAPI($json);
            } elseif ($postArr['MsgType'] == 'event' && $postArr['Event'] == 'user_enter_tempsession') { //用户进入客服
                $fromUsername = $postArr['FromUserName'];   //此处为文字回复，不同的回复方式可参考文章顶部第三个链接“回复客户消息”里查看
                $content = '你好,你的专属海报正在制作中,请稍后回复“1”获取海报';
                $data = array(
                    "touser" => $fromUsername,
                    "msgtype" => "text",
                    "text" => array("content" => $content)
                );
                $json = json_encode($data, JSON_UNESCAPED_UNICODE);  //php5.4+
                $this->requestAPI($json);
            } else {
                exit('error');
            }
        } else {
            echo "empty";
            exit;
        }

    }
    protected function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }

    }
    protected function requestAPI($json){
        $access_token = $this->get_accessToken();
        /*
         * POST发送https请求客服接口api
         */
        $url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$access_token;
        //以'json'格式发送post的https请求
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($json)){
            curl_setopt($curl, CURLOPT_POSTFIELDS,$json);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
        $output = curl_exec($curl);
        if (curl_errno($curl)) {
            echo 'Errno'.curl_error($curl);//捕抓异常
        }
        curl_close($curl);
        if($output == 0){
            echo 'success';exit;
        }
    }


    protected function get_accessToken()
    {
        $config = config('site.wxapp');

        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['wxappid'].'&secret=' . $config['wxappsecret'];
        @$weixin = file_get_contents($url);
        @$jsondecode = json_decode($weixin);
        @$array = get_object_vars($jsondecode);
        $token = $array['access_token'];
        return $token;
    }

}
